import {
  fetchArticleComments,
  fetchArticleDetail,
  fetchCommentsReply,
  putArticleComment,
  putCommentReply,
} from '@/services/api/passage'
import {
  type ArticleDetail,
  type ArticleTopComment,
  type CommentReply,
} from '@/utils/dataType/ArticleModel'
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { reactive } from 'vue'

/**游记文章管理中心
 * 功能如下：
 * 1.降低后端请求处理
 * 2.增加缓存处理机制
 * 3.用户强制刷新
 * 4.定期监控清理
 */
export const useArticleManageStore = defineStore('ArticleManageCenter', {
  state: () => ({
    //文章数据
    articles: {} as Record<number, ArticleDetail>,

    //评论数据+分页结构
    comments: reactive({}) as Record<
      number,
      {
        data: ArticleTopComment[]
        pagination: {
          page: number
          pageSize: number
          total: number
        }
      }
    >,

    //回复数据
    replies: reactive({}) as Record<number, CommentReply[]>,

    //缓存控制
    cacheConfig: {
      articles: {
        lastUpdated: new Map<number, number>(),
        ttl: 1000 * 60 * 60 * 24,
      },
      comments: {
        lastUpdated: new Map<number, number>(),
        ttl: 1000 * 60 * 2,
      },
      replies: {
        lastUpdated: new Map<number, number>(),
        ttl: 1000 * 60 * 2,
      },
    },

    cleanupConfig: {
      interval: 1000 * 60 * 30,
      lastCleanup: 0,
      maxItems: {
        articles: 50,
        comments: 100,
        replies: 200,
      },
    },

    loadingStates: {
      articles: new Map<number, 'idle' | 'loading' | 'error'>(),
      comments: new Map<number, 'idle' | 'loading' | 'error'>(),
      replies: new Map<number, 'idle' | 'loading' | 'error'>(),
    },
    postingStates: {
      comments: new Map<number, 'idle' | 'posting' | 'error'>(),
      replies: new Map<number, 'idle' | 'posting' | 'error'>(),
    },
  }),
  getters: {
    isCacheValid: (state) => (type: 'articles' | 'comments' | 'replies', id: number) => {
      const lastUpdated = state.cacheConfig[type].lastUpdated.get(id)
      return !!lastUpdated && Date.now() - lastUpdated < state.cacheConfig[type].ttl
    },
  },
  actions: {
    checkCleanup() {
      if (Date.now() - this.cleanupConfig.lastCleanup > this.cleanupConfig.interval) {
        this.autoCleanup()
      }
    },
    autoCleanup() {},
    async fetchArticle(articleId: number, forceRefresh = false) {
      if (!forceRefresh && this.isCacheValid('articles', articleId)) {
        return this.articles[articleId]
      }
      this.loadingStates.articles.set(articleId, 'loading')
      try {
        const res = await fetchArticleDetail({ articleId })
        if (res.data != null && res.data.length != 0) {
          this.loadingStates.articles.set(articleId, 'idle')
          this.articles[articleId] = res.data.data
          this.cacheConfig.articles.lastUpdated.set(articleId, Date.now())
          return res.data
        }
      } catch (error) {
        this.loadingStates.articles.set(articleId, 'error')
        ElMessage.error('获取文章失败: ' + error)
        console.error('获取文章失败:', error)
      }
    },
    async fetchComments(articleId: number, page = 1, pageSize = 10, forceRefresh = false) {
      if (!forceRefresh && this.isCacheValid('comments', articleId)) {
        console.log('本地缓存获取评论区')
        return this.comments[articleId]
      }
      this.loadingStates.comments.set(articleId, 'loading')
      try {
        const res = await fetchArticleComments({ articleId, page, pageSize })
        this.comments[articleId] = {
          data: res.data.records,
          pagination: {
            page,
            pageSize,
            total: res.data.total,
          },
        }
        this.cacheConfig.comments.lastUpdated.set(articleId, Date.now())
        this.loadingStates.comments.set(articleId, 'idle')
        return this.comments[articleId]
      } catch (error) {
        this.loadingStates.comments.set(articleId, 'error')
        console.error('[获取文章评论]:出错了->', error)
      }
    },
    async fetchReply(commentId: number, forceRefresh = false) {
      if (!forceRefresh && this.isCacheValid('replies', commentId)) {
        return this.replies[commentId]
      }
      this.loadingStates.replies.set(commentId, 'loading')
      try {
        const res = await fetchCommentsReply({ topId: commentId })
        this.replies[commentId] = res.data
        this.cacheConfig.replies.lastUpdated.set(commentId, Date.now())
        this.loadingStates.replies.set(commentId, 'idle')
        return this.replies[commentId]
      } catch (error) {
        this.loadingStates.replies.set(commentId, 'error')
        console.error('[获取回复评论]:失败->', error)
      }
    },
    async postComment(articleId: number, comment: string) {
      this.postingStates.comments.set(articleId, 'posting')
      try {
        await putArticleComment({ articleId, comment })
        this.postingStates.comments.set(articleId, 'idle')
        const commentData = await this.fetchComments(articleId, 1, 10, true)
        // this.comments[articleId] = { ...commentData }
        Object.assign(this.comments[articleId], { ...commentData })
        console.log('提交后的文章评论为:', this.comments[articleId])
      } catch (error) {
        this.postingStates.comments.set(articleId, 'error')
        console.error('[提交评论]:出错了->', error)
      }
    },
    async postReply(articleId: number, content: string, commentId: number) {
      this.postingStates.replies.set(commentId, 'posting')
      try {
        await putCommentReply({ articleId, content, parentId: commentId })
        this.postingStates.replies.set(commentId, 'idle')
        const replyData = this.fetchReply(commentId, true)
        Object.assign(this.replies[commentId], { ...replyData })
        console.log('提交后的回复数据为:', this.replies[commentId])
      } catch (error) {
        this.postingStates.replies.set(commentId, 'error')
        console.error('[提交回复]:失败->', error)
      }
    },
  },
})
